package com.ecy.quadratic.ui.presenter;

import android.content.Context;

import com.ecy.quadratic.api.ComicApi;
import com.ecy.quadratic.beans.Comic;
import com.ecy.quadratic.beans.ComicBroswer;
import com.ecy.quadratic.beans.ComicSectionDetail;
import com.ecy.quadratic.beans.ComicSectionDetailResponseBean;
import com.ecy.quadratic.beans.SectionBean;
import com.ecy.quadratic.manager.BroswerManager;
import com.ecy.quadratic.manager.EventManager;
import com.ecy.quadratic.manager.SettingManager;
import com.ecy.quadratic.reader.ReaderApplication;
import com.ecy.quadratic.reader.base.RxPresenter;
import com.ecy.quadratic.reader.utils.ACache;
import com.ecy.quadratic.reader.utils.RxUtil;
import com.ecy.quadratic.reader.utils.StringUtils;
import com.ecy.quadratic.ui.contract.ComicReadContract;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ComicReadPresenter extends RxPresenter<ComicReadContract.View>
        implements ComicReadContract.Presenter<ComicReadContract.View> {

    private Context mContext;
    private ComicApi comicApi;

    @Inject
    public ComicReadPresenter(Context mContext, ComicApi comicApi) {
        this.mContext = mContext;
        this.comicApi = comicApi;
    }

    @Override
    public void saveReadingSection(final String comicId, final String comicTitle, final String comicCover, final SectionBean sectionBean) {
        Subscription subscription = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                String key = StringUtils.creatAcacheKey("comic_reading_section", comicId, SettingManager.getInstance().getUserChooseSex());

                ACache.get(ReaderApplication.getsInstance()).put(key, new Gson().toJson(sectionBean, SectionBean.class));
                EventManager.refreshReadingSection(sectionBean);
                ComicBroswer broswer = new ComicBroswer();
                broswer.setReadingSectionBean(sectionBean);
                Comic comic = new Comic();
                comic.setId(comicId);
                comic.setTitle(comicTitle);
                comic.setImg(comicCover);
                broswer.setAffiliatedComic(comic);
                BroswerManager.getInstance().add(broswer);
                subscriber.onNext("");
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {

                    }
                });

        addSubscrebe(subscription);

    }

    @Override
    public void getImageUrl(String imgId, final boolean isPreSection) {
        mView.showLoadingView();
        String key = StringUtils.creatAcacheKey("comic_chatper_img-list", imgId, SettingManager.getInstance().getUserChooseSex());
        Observable<ComicSectionDetailResponseBean> fromNetWork = comicApi.getComicChapterImgs(imgId)
                .compose(RxUtil.<ComicSectionDetailResponseBean>rxCacheBeanHelper(key));

        //依次检查disk、network
        Subscription rxSubscription = Observable.concat(RxUtil.rxCreateDiskObservable(key, ComicSectionDetailResponseBean.class), fromNetWork)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ComicSectionDetailResponseBean>() {
                    @Override
                    public void onNext(ComicSectionDetailResponseBean secionDetail) {
                        if (secionDetail != null) {
                            List<ComicSectionDetail> list = secionDetail.getResult();
                            if (list != null && mView != null) {
                                mView.showImgList(list, isPreSection);

                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
//                        ToastUtils.getToast("error", Toast.LENGTH_SHORT).show();
                        mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }

    @Override
    public void getImageUrl(final SectionBean sectionbean, final boolean isPreSection) {

        Observable.create(new Observable.OnSubscribe<List>() {
            @Override
            public void call(Subscriber<? super List> subscriber) {
                int startNum = sectionbean.getStart_num();
                int endNum = sectionbean.getEnd_num();
                List<String> list = new ArrayList<String>();
                for (int i = startNum; i <= endNum; i++) {
                    String rule = sectionbean.getRule();
                    String url = rule.replace("$$", i + "");
                    String imgUrl = url;
                    if (url.length() > 9) {
                        imgUrl = url.substring(0, 9);
                        String[] result = url.substring(9).split("/");
                        for (int index = 0; index < result.length - 1; index++) {
                            try {
                                imgUrl = imgUrl + URLEncoder.encode(result[index], "utf-8") + "/";
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (result != null && result.length > 0) {
                            imgUrl = imgUrl + result[result.length - 1];
                        }

                    }
                    list.add(imgUrl);
                }
                subscriber.onNext(list);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError();
                    }

                    @Override
                    public void onNext(List list) {
                        if (list != null && mView != null) {
                            mView.showKMImgList(list, isPreSection);

                        }
                    }
                });

    }
}